// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.SalesWithdraw;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.SalesWithdrawMapper;
import com.fowo.api.mapper.SalesWithdrawProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.sales.withdraw.SalesWithdrawBatchCancellationAction;
import com.fowo.api.model.sales.withdraw.SalesWithdrawBatchImportreceiveAction;
import com.fowo.api.model.sales.withdraw.SalesWithdrawBatchImportrecordAction;
import com.fowo.api.model.sales.withdraw.SalesWithdrawBatchSyncBillAction;
import com.fowo.api.model.sales.withdraw.SalesWithdrawExcelPo;
import com.fowo.api.model.sales.withdraw.SalesWithdrawImportPo;
import com.fowo.api.model.sales.withdraw.SalesWithdrawItemVo;
import com.fowo.api.model.sales.withdraw.SalesWithdrawSearchParamPo;
import com.fowo.api.model.sales.withdraw.SalesWithdrawVo;
import com.fowo.api.model.sales.withdraw.SalesWithdrawZuofeiAction;
import com.fowo.api.model.sales.withdraw.constant.SalesWithdrawAfterSaleTypeEnums;
import com.fowo.api.model.sales.withdraw.constant.SalesWithdrawHasPredictionEnums;
import com.fowo.api.model.sales.withdraw.constant.SalesWithdrawSalesTypeEnums;
import com.fowo.api.model.sales.withdraw.constant.SalesWithdrawStatusEnums;
import com.fowo.api.model.sales.withdraw.product.SalesWithdrawProductItemVo;
import com.fowo.api.model.sales.withdraw.product.SalesWithdrawProductItemVoPages;
import com.fowo.api.model.sales.withdraw.product.SalesWithdrawProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.SalesWithdrawProductService;
import com.fowo.api.service.SalesWithdrawService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 销售退货单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：李玉娇
 */
@Slf4j
@DataObjectType(SalesWithdraw.class)
@DS("ds24")
public class SalesWithdrawBaseServiceImpl
  extends ServiceImpl<SalesWithdrawMapper, SalesWithdraw>
  implements SalesWithdrawService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("whnameName", "w.`name`");
      put("storeNameShopName", "si.`shop_name`");
      put("createUserName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected SalesWithdrawService self;

  @Resource
  protected SalesWithdrawProductService salesWithdrawProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected SalesWithdrawBatchSyncBillAction salesWithdrawBatchSyncBillAction;

  @Autowired(required = false)
  protected SalesWithdrawBatchCancellationAction salesWithdrawBatchCancellationAction;

  @Autowired(required = false)
  protected SalesWithdrawBatchImportreceiveAction salesWithdrawBatchImportreceiveAction;

  @Autowired(required = false)
  protected SalesWithdrawZuofeiAction salesWithdrawZuofeiAction;

  @Autowired(required = false)
  protected SalesWithdrawBatchImportrecordAction salesWithdrawBatchImportrecordAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected Validator validator;

  /**
   * 创建销售退货单
   * @param model 销售退货单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(SalesWithdrawVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SalesWithdraw entity = new SalesWithdraw();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("0");
    }

    if (model.getAfterSaleType() == null) {
      entity.setAfterSaleType("1");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getRmaOrderNo())) {
      entity.setRmaOrderNo(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "SalesWithdraw.rmaOrderNo")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("销售退货单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 销售退货单
   */
  protected void updateAllChilds(SalesWithdrawVo model) throws Exception {
    if (model.getLists() != null) {
      salesWithdrawProductService.saveAllByParentSalesWithdraw(
        model.getId(),
        model.getLists()
      );
    }
  }

  /**
   * 更新销售退货单
   * @param model 销售退货单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(SalesWithdrawVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SalesWithdraw entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("销售退货单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "createUser",
      "createTime",
      "id",
      "lastUpdateUser",
      "lastUpdateTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新销售退货单（带空值）
   * @param model 销售退货单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(SalesWithdrawVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SalesWithdraw entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("销售退货单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(SalesWithdraw::getRmaOrderNo, model.getRmaOrderNo())
      .set(SalesWithdraw::getSalesType, model.getSalesType())
      .set(SalesWithdraw::getWhname, model.getWhname())
      .set(SalesWithdraw::getStoreName, model.getStoreName())
      .set(SalesWithdraw::getGlobalOrderNo, model.getGlobalOrderNo())
      .set(SalesWithdraw::getReason, model.getReason())
      .set(SalesWithdraw::getStatus, model.getStatus())
      .set(
        SalesWithdraw::getLogisticsProviderName,
        model.getLogisticsProviderName()
      )
      .set(SalesWithdraw::getTrackingNo, model.getTrackingNo())
      .set(SalesWithdraw::getPreArrivalTime, model.getPreArrivalTime())
      .set(SalesWithdraw::getHasPrediction, model.getHasPrediction())
      .set(SalesWithdraw::getRemark, model.getRemark())
      .set(SalesWithdraw::getLogisticsType, model.getLogisticsType())
      .set(SalesWithdraw::getSite, model.getSite())
      .set(SalesWithdraw::getPlatform, model.getPlatform())
      .set(SalesWithdraw::getLastUpdateUser, model.getLastUpdateUser())
      .set(SalesWithdraw::getLastUpdateTime, model.getLastUpdateTime())
      .set(SalesWithdraw::getWname, model.getWname())
      .set(SalesWithdraw::getSname, model.getSname())
      .eq(SalesWithdraw::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(SalesWithdrawSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 退货单商品子表(lists) 对应的对象
    SalesWithdrawProductSearchParamPo listsSearchParam =
      new SalesWithdrawProductSearchParamPo();
    listsSearchParam.setDisableDataPremissions(true);
    listsSearchParam.setParentSalesWithdrawInList(ids);
    SalesWithdrawProductMapper localSalesWithdrawProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(SalesWithdrawProductMapper.class);
    listsSearchParam.applySqlSegments();
    List<Long> listsIdList = localSalesWithdrawProductMapper.searchIds(
      listsSearchParam
    );
    if (!listsIdList.isEmpty()) {
      SalesWithdrawProductService localSalesWithdrawProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(SalesWithdrawProductService.class);
      localSalesWithdrawProductService.batchDelete(listsIdList);
    }
  }

  /**
   * 删除销售退货单
   * @param id 销售退货单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除销售退货单
   * @param ids 销售退货单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<SalesWithdrawImportPo> excelToImportRow(
    SalesWithdrawImportPo row,
    Integer rowNumber,
    SalesWithdrawVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<SalesWithdrawImportPo> ir =
      new ImportRow<SalesWithdrawImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<SalesWithdrawImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new SalesWithdrawVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, SalesWithdrawImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getSalesType())) {
      vo.setSalesType(SalesWithdrawSalesTypeEnums.toValue(row.getSalesType()));
      if (vo.getSalesType() == null) {
        ir.addError("salesType", "退货类型只能是：“买家退货”, “物流退货”");
      }
    }
    if (StringUtils.hasText(row.getStatus())) {
      vo.setStatus(SalesWithdrawStatusEnums.toValue(row.getStatus()));
      if (vo.getStatus() == null) {
        ir.addError("status", "订单状态只能是：“待收货”, “已完成”, “已作废”");
      }
    }
    vo.setPreArrivalTime(SheetUtils.tryToDateTime(row.getPreArrivalTime()));
    if (StringUtils.hasText(row.getHasPrediction())) {
      vo.setHasPrediction(
        SalesWithdrawHasPredictionEnums.toValue(row.getHasPrediction())
      );
      if (vo.getHasPrediction() == null) {
        ir.addError("hasPrediction", "三方仓预报只能是：“不预报”, “预报”");
      }
    }
    vo.setSid(SheetUtils.tryToLong(row.getSid()));
    vo.setWid(SheetUtils.tryToLong(row.getWid()));
    if (StringUtils.hasText(row.getAfterSaleType())) {
      vo.setAfterSaleType(
        SalesWithdrawAfterSaleTypeEnums.toValue(row.getAfterSaleType())
      );
      if (vo.getAfterSaleType() == null) {
        ir.addError(
          "afterSaleType",
          "售后类型只能是：“退货退款”, “退款”, “退货”"
        );
      }
    }
    // 处理关联字段“退货仓库”
    if (
      !SheetUtils.isBlank(row.getWhnameName()) &&
      SheetUtils.isBlank(row.getWhname())
    ) {
      WarehouseSearchParamPo whnameSearchParam = new WarehouseSearchParamPo();
      whnameSearchParam.setLimit(2); // 最大只返回二行记录
      whnameSearchParam.setNameEq(SheetUtils.trim(row.getWhnameName()));
      whnameSearchParam.applySqlSegments();
      List<WarehouseItemVo> whnameMatches = warehouseMapper.search(
        whnameSearchParam
      );
      if (whnameMatches.size() == 0) {
        ir.addError("whnameName", "未能在仓库即时库存中找到匹配的数据");
      } else if (whnameMatches.size() > 1) {
        ir.addError(
          "whnameName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWhname(whnameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", whnameMatches.get(0).getId())
          .put("fromObjectName", "SalesWithdraw")
          .put("fromObjectId", vo.getId())
          .put("fromField", "whname")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("wname")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("name")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("wname")
              .rowFieldName("wname")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(whnameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getStoreNameShopName()) &&
      SheetUtils.isBlank(row.getStoreName())
    ) {
      ShopInfoSearchParamPo storeNameSearchParam = new ShopInfoSearchParamPo();
      storeNameSearchParam.setLimit(2); // 最大只返回二行记录
      storeNameSearchParam.setShopNameEq(
        SheetUtils.trim(row.getStoreNameShopName())
      );
      storeNameSearchParam.applySqlSegments();
      List<ShopInfoItemVo> storeNameMatches = shopInfoMapper.search(
        storeNameSearchParam
      );
      if (storeNameMatches.size() == 0) {
        ir.addError("storeNameShopName", "未能在店铺中找到匹配的数据");
      } else if (storeNameMatches.size() > 1) {
        ir.addError(
          "storeNameShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setStoreName(storeNameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", storeNameMatches.get(0).getId())
          .put("fromObjectName", "SalesWithdraw")
          .put("fromObjectId", vo.getId())
          .put("fromField", "storeName")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sname")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("shopName")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sname")
              .rowFieldName("sname")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(storeNameMatches),
          joinModels
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<SalesWithdrawImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<SalesWithdrawImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            SalesWithdrawImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              SalesWithdrawImportPo row,
              AnalysisContext cxt
            ) {
              SalesWithdrawVo vo = new SalesWithdrawVo();
              ImportRow<SalesWithdrawImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<SalesWithdrawImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<SalesWithdrawImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      SalesWithdrawVo vo = new SalesWithdrawVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"退货单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "rmaOrderNo".equals(m.getField())
          )
      ) {
        vo.setRmaOrderNo(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "SalesWithdraw.rmaOrderNo")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    SalesWithdrawSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "salesType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SalesWithdrawSalesTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "whname",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SalesWithdrawItemVo) r).getWhnameName())
          )
      );
      exportOptions.addFieldMappingOption(
        "storeName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SalesWithdrawItemVo) r).getStoreNameShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> SalesWithdrawStatusEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "hasPrediction",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SalesWithdrawHasPredictionEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "rmaOrderNo",
        "salesType",
        "whnameName",
        "storeNameShopName",
        "globalOrderNo",
        "reason",
        "status",
        "logisticsProviderName",
        "trackingNo",
        "hasPrediction",
        "remark",
        "wname",
        "sname"
      );

      String fileName = String.format(
        "销售退货单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<SalesWithdrawExcelPo> items = new ArrayList<SalesWithdrawExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<SalesWithdrawItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<SalesWithdrawItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (SalesWithdrawItemVo item : list) {
        SalesWithdrawExcelPo excel = new SalesWithdrawExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setSalesType(
          SalesWithdrawSalesTypeEnums.toLabel(item.getSalesType())
        );
        excel.setStatus(SalesWithdrawStatusEnums.toLabel(item.getStatus()));
        excel.setHasPrediction(
          SalesWithdrawHasPredictionEnums.toLabel(item.getHasPrediction())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "销售退货单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(SalesWithdrawExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过系统单号查询销售退货单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByGlobalOrderNo(String globalOrderNo) {
    return this.baseMapper.getIdByGlobalOrderNo(globalOrderNo);
  }

  /**
   * 通过系统单号查询销售退货单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByGlobalOrderNo(List<String> list) {
    return this.baseMapper.getIdsByGlobalOrderNo(list);
  }

  /**
   * 通过销售退货单主键查询系统单号
   */
  @Override
  public String getGlobalOrderNoById(Long id) {
    return this.baseMapper.getGlobalOrderNoById(id);
  }

  /**
   * 通过销售退货单主键查询系统单号列表
   */
  @Override
  public List<String> getGlobalOrderNoByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getGlobalOrderNoByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("globalOrderNo"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 销售退货单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public SalesWithdrawVo getVoById(Long id) throws Exception {
    SalesWithdrawVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    SalesWithdrawProductSearchParamPo listsSearchParamPo =
      new SalesWithdrawProductSearchParamPo();
    listsSearchParamPo.setParentSalesWithdraw(id);
    listsSearchParamPo.getExtendData().put("queryMode", "sub");
    listsSearchParamPo.getExtendData().put("queryParent", "SalesWithdraw");
    listsSearchParamPo.applySqlSegments();
    vo.setLists(salesWithdrawProductService.search(listsSearchParamPo));

    return vo;
  }

  /**
   * 分页查询销售退货单
   * @param search 查询条件
   * @return 销售退货单分页查询结果
   */
  @Override
  public Page<SalesWithdrawItemVo> pageSearch(
    SalesWithdrawSearchParamPo search
  ) {
    Page<SalesWithdrawItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(SalesWithdrawItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<SalesWithdrawItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<SalesWithdrawItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    SalesWithdrawProductSearchParamPo listsSearchParamPo =
      new SalesWithdrawProductSearchParamPo();
    listsSearchParamPo.setSort(sort);
    listsSearchParamPo.setPageSize(200);
    listsSearchParamPo.setParentSalesWithdrawInList(
      pageResult
        .getRecords()
        .stream()
        .map(SalesWithdrawItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<SalesWithdrawProductItemVoPages>> listsMaps =
      salesWithdrawProductService.pagesByParentSalesWithdraw(
        listsSearchParamPo
      );

    for (SalesWithdrawItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put("lists", listsMaps.get(itemVo.getId().toString()));
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 销售退货单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(SalesWithdrawSearchParamPo search) {
    return appendWithChild(pageSearch(search), search.toChildSort("lists"));
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    SalesWithdrawSearchParamPo search
  ) {
    SalesWithdrawSearchParamPo parentSearchParam =
      new SalesWithdrawSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<SalesWithdrawItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      SalesWithdrawItemVo itemVo = parentList.get(0);

      SalesWithdrawProductSearchParamPo listsSearchParamPo =
        new SalesWithdrawProductSearchParamPo();
      listsSearchParamPo.setPageSize(search.getPageSize());
      listsSearchParamPo.setCurrent(search.getCurrent());
      listsSearchParamPo.setParentSalesWithdraw(itemVo.getId());
      return salesWithdrawProductService.pageSearch(listsSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 销售退货单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'SalesWithdrawOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<SalesWithdrawItemVo>> searchOptions(
    SalesWithdrawSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询销售退货单
   * @param search 查询条件
   * @return 销售退货单列表查询结果
   */
  @Override
  public List<SalesWithdrawItemVo> search(SalesWithdrawSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询销售退货单最后更新时间
   * @param search 查询条件
   * @return 销售退货单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(SalesWithdrawSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 同步单据
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步单据操作"
  )
  @Override
  public void batchSyncBill(List<Long> ids) throws Exception {
    if (salesWithdrawBatchSyncBillAction == null) {
      throw new Exception("此操作当前不可用");
    }
    salesWithdrawBatchSyncBillAction.run(ids);
  }

  /**
   * 批量作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量作废操作"
  )
  @Override
  public void batchCancellation(List<Long> ids) throws Exception {
    if (salesWithdrawBatchCancellationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    salesWithdrawBatchCancellationAction.run(ids);
  }

  /**
   * 导入收货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了导入收货操作"
  )
  @Override
  public void batchImportreceive(List<Long> ids) throws Exception {
    if (salesWithdrawBatchImportreceiveAction == null) {
      throw new Exception("此操作当前不可用");
    }
    salesWithdrawBatchImportreceiveAction.run(ids);
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void zuofei(Long id) throws Exception {
    if (salesWithdrawZuofeiAction == null) {
      throw new Exception("此操作当前不可用");
    }
    salesWithdrawZuofeiAction.run(id);
  }

  /**
   * 导入记录
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了导入记录操作"
  )
  @Override
  public void batchImportrecord(List<Long> ids) throws Exception {
    if (salesWithdrawBatchImportrecordAction == null) {
      throw new Exception("此操作当前不可用");
    }
    salesWithdrawBatchImportrecordAction.run(ids);
  }

  /**
   * 全部
   */
  @Override
  public List<SalesWithdrawItemVo> allOrders(
    SalesWithdrawSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allOrders(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<SalesWithdrawItemVo> allOrdersPage(
    SalesWithdrawSearchParamPo search
  ) {
    Page<SalesWithdrawItemVo> allOrdersPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allOrdersPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allOrdersPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allOrdersPage =
      this.baseMapper.allOrdersPage(
          search.toPage(this.baseMapper.allOrdersCount(search)),
          search
        );
    List<Long> recordIds = allOrdersPage
      .getRecords()
      .stream()
      .map(SalesWithdrawItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allOrdersPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allOrdersPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allOrdersPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allOrdersPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 销售退货单分页查询结果
   */
  @Override
  public Page<?> allOrdersPageWithChildSearch(
    SalesWithdrawSearchParamPo search
  ) {
    return appendWithChild(allOrdersPage(search), search.toChildSort("lists"));
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allOrdersLastUpdateTime(SalesWithdrawSearchParamPo search) {
    return this.baseMapper.allOrdersLastUpdateTime(search);
  }

  /**
   * 待收货
   */
  @Override
  public List<SalesWithdrawItemVo> waitReceived(
    SalesWithdrawSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitReceived(search);
  }

  /**
   * 待收货分页
   */
  @Override
  public Page<SalesWithdrawItemVo> waitReceivedPage(
    SalesWithdrawSearchParamPo search
  ) {
    Page<SalesWithdrawItemVo> waitReceivedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitReceivedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitReceivedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitReceivedPage =
      this.baseMapper.waitReceivedPage(
          search.toPage(this.baseMapper.waitReceivedCount(search)),
          search
        );
    List<Long> recordIds = waitReceivedPage
      .getRecords()
      .stream()
      .map(SalesWithdrawItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitReceivedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitReceivedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitReceivedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitReceivedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 销售退货单分页查询结果
   */
  @Override
  public Page<?> waitReceivedPageWithChildSearch(
    SalesWithdrawSearchParamPo search
  ) {
    return appendWithChild(
      waitReceivedPage(search),
      search.toChildSort("lists")
    );
  }

  /**
   * 查询待收货最后更新时间
   * @param search 查询条件
   * @return 待收货最后更新时间
   */
  @Override
  public Date waitReceivedLastUpdateTime(SalesWithdrawSearchParamPo search) {
    return this.baseMapper.waitReceivedLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<SalesWithdrawItemVo> completed(
    SalesWithdrawSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.completed(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<SalesWithdrawItemVo> completedPage(
    SalesWithdrawSearchParamPo search
  ) {
    Page<SalesWithdrawItemVo> completedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completedPage =
      this.baseMapper.completedPage(
          search.toPage(this.baseMapper.completedCount(search)),
          search
        );
    List<Long> recordIds = completedPage
      .getRecords()
      .stream()
      .map(SalesWithdrawItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 销售退货单分页查询结果
   */
  @Override
  public Page<?> completedPageWithChildSearch(
    SalesWithdrawSearchParamPo search
  ) {
    return appendWithChild(completedPage(search), search.toChildSort("lists"));
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date completedLastUpdateTime(SalesWithdrawSearchParamPo search) {
    return this.baseMapper.completedLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<SalesWithdrawItemVo> obsolete(SalesWithdrawSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.obsolete(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<SalesWithdrawItemVo> obsoletePage(
    SalesWithdrawSearchParamPo search
  ) {
    Page<SalesWithdrawItemVo> obsoletePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return obsoletePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return obsoletePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    obsoletePage =
      this.baseMapper.obsoletePage(
          search.toPage(this.baseMapper.obsoleteCount(search)),
          search
        );
    List<Long> recordIds = obsoletePage
      .getRecords()
      .stream()
      .map(SalesWithdrawItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return obsoletePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return obsoletePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    obsoletePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return obsoletePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 销售退货单分页查询结果
   */
  @Override
  public Page<?> obsoletePageWithChildSearch(
    SalesWithdrawSearchParamPo search
  ) {
    return appendWithChild(obsoletePage(search), search.toChildSort("lists"));
  }

  /**
   * 查询已作废最后更新时间
   * @param search 查询条件
   * @return 已作废最后更新时间
   */
  @Override
  public Date obsoleteLastUpdateTime(SalesWithdrawSearchParamPo search) {
    return this.baseMapper.obsoleteLastUpdateTime(search);
  }

  /**
   * 更新状态为2
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object updateSalesWithdrawStatus(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/SalesWithdraw_UpdateSalesWithdrawStatus.js",
      args,
      this
    );
  }

  /**
   * 关联单据(入库单)
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object getStockInByRamNo(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/SalesWithdraw_GetStockInByRamNo.js",
      args,
      this
    );
  }

  /**
   * 根据id获取主子表信息
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object getSalesWithdrawOrdersById(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/SalesWithdraw_GetSalesWithdrawOrdersById.js",
      args,
      this
    );
  }
}
